//
//  ZHPickView.m
//  ZHpickView
//
//  Created by liudianling on 14-11-18.
//  Copyright (c) 2014年 赵恒志. All rights reserved.
//
// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com

#import "ZHPickView.h"

#define BMUIHexColor(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

@implementation ZHPickView

-(NSArray *)plistArray
{
    if (_plistArray==nil) {
        _plistArray=[[NSArray alloc] init];
    }
    return _plistArray;
}

-(NSArray *)componentArray
{
    if (_componentArray==nil) {
        _componentArray=[[NSMutableArray alloc] init];
    }
    return _componentArray;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUpToolBar];
    }
    return self;
}

-(instancetype)initPickviewWithPlistName:(NSString *)plistName isHaveNavControler:(BOOL)isHaveNavControler{
    
    self=[super init];
    if (self) {
        _plistName = plistName;
        self.plistArray = [self getPlistArrayByplistName:plistName];
        [self setUpPickView];
        [self setFrameWith:isHaveNavControler];
    }
    return self;
}

//手动添加院校数组
-(instancetype)initPickviewYuanxiaoWithPlistName:(NSMutableArray *)yuanxiaoArray isHaveNavControler:(BOOL)isHaveNavControler{
    self=[super init];
    if (self) {
        self.plistArray=yuanxiaoArray;
        [self setArrayClass:yuanxiaoArray];
        [self setUpPickView];
        [self setFrameWith:isHaveNavControler];
    }
    return self;
}

-(instancetype)initPickviewWithArray:(NSArray *)array isHaveNavControler:(BOOL)isHaveNavControler{
    self=[super init];
    if (self) {
        self.plistArray = array;
        [self setArrayClass:array];
        [self setUpPickView];
        [self setFrameWith:isHaveNavControler];
    }
    return self;
}

-(instancetype)initDatePickWithDate:(NSDate *)defaulDate datePickerMode:(UIDatePickerMode)datePickerMode isHaveNavControler:(BOOL)isHaveNavControler
{
    self=[super init];
    if (self) {
        _defaulDate = defaulDate;
        [self setUpDatePickerWithdatePickerMode:(UIDatePickerMode)datePickerMode];
        [self setFrameWith:isHaveNavControler];
    }
    return self;
}

-(NSArray *)getPlistArrayByplistName:(NSString *)plistName{
    
    NSString *path = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"];
    NSArray * array = [[NSArray alloc] initWithContentsOfFile:path];
    [self setArrayClass:array];
    return array;
}

-(void)setArrayClass:(NSArray *)array{
    _dicKeyArray=[[NSMutableArray alloc] init];
    for (id levelTwo in array) {
        
        if ([levelTwo isKindOfClass:[NSArray class]]) {
            _isLevelArray=YES;
            _isLevelString=NO;
            _isLevelDic=NO;
        }else if ([levelTwo isKindOfClass:[NSString class]]){
            _isLevelString=YES;
            _isLevelArray=NO;
            _isLevelDic=NO;
            
        }else if ([levelTwo isKindOfClass:[NSDictionary class]])
        {
            _isLevelDic=YES;
            _isLevelString=NO;
            _isLevelArray=NO;
            _levelTwoDic=levelTwo;
            [_dicKeyArray addObject:[_levelTwoDic allKeys] ];
        }
    }
}

-(void)setFrameWith:(BOOL)isHaveNavControler
{
    CGFloat toolViewH = _pickeviewHeight+ZHToobarHeight;
    self.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height,  [UIScreen mainScreen].bounds.size.width, toolViewH);
}

-(void)setUpPickView
{
    UIPickerView *pickView = [[UIPickerView alloc] init];
    pickView.backgroundColor = [UIColor whiteColor];
    _pickerView = pickView;
    pickView.delegate = self;
    pickView.dataSource = self;
    pickView.frame = CGRectMake(0, ZHToobarHeight, [UIScreen mainScreen].bounds.size.width, pickView.frame.size.height);
    _pickeviewHeight = pickView.frame.size.height;
    [self addSubview:pickView];
}

-(void)setUpDatePickerWithdatePickerMode:(UIDatePickerMode)datePickerMode
{
    UIDatePicker *datePicker = [[UIDatePicker alloc] init];
    datePicker.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    datePicker.datePickerMode = datePickerMode;
    datePicker.backgroundColor = [UIColor whiteColor];
    if (_defaulDate) {
        [datePicker setDate:_defaulDate];
    }
    _datePicker=datePicker;
    datePicker.frame=CGRectMake(0, ZHToobarHeight, [UIScreen mainScreen].bounds.size.width, datePicker.frame.size.height);
    _pickeviewHeight=datePicker.frame.size.height;
    [self addSubview:datePicker];
}
-(void)setUpToolBar
{
    _toolbarView = [self setToolbarStyle];
    [self setToolbarWithPickViewFrame];
    [self addSubview:_toolbarView];
}

-(UIView *)setToolbarStyle
{
    UIView *toolBarView = [[UIView alloc]init];
    toolBarView.backgroundColor = [UIColor whiteColor];
    
    //取消按钮
    UIButton *cancelItem = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelItem.frame = CGRectMake(0, 1, 50,ZHToobarHeight-1);
    cancelItem.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [cancelItem setTitle:@"取消" forState:UIControlStateNormal];
    [cancelItem setTitleColor:BMUIHexColor(0x666666) forState:UIControlStateNormal];
    [cancelItem addTarget:self action:@selector(remove) forControlEvents:UIControlEventTouchUpInside];
    [toolBarView addSubview:cancelItem];
    
    //确定按钮
    UIButton *doneItem = [UIButton buttonWithType:UIButtonTypeCustom];
    doneItem.frame = CGRectMake( [UIScreen mainScreen].bounds.size.width - 50, 1, 50, ZHToobarHeight-1);
    [doneItem setTitle:@"确定" forState:UIControlStateNormal];
    doneItem.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [doneItem setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [doneItem addTarget:self action:@selector(doneClick) forControlEvents:UIControlEventTouchUpInside];
    [toolBarView addSubview:doneItem];
    
    //标题
    self.pickerTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(50,1,  [UIScreen mainScreen].bounds.size.width -100,ZHToobarHeight-1)];
    self.pickerTitleLabel.textAlignment = NSTextAlignmentCenter;
    self.pickerTitleLabel.backgroundColor = [UIColor clearColor];
    self.pickerTitleLabel.textColor = BMUIHexColor(0x666666);
    self.pickerTitleLabel.font = [UIFont boldSystemFontOfSize:15];
    [toolBarView addSubview:self.pickerTitleLabel];
    
    return toolBarView;
}

-(void)setToolbarWithPickViewFrame
{
    _toolbarView.frame=CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, ZHToobarHeight);
}

-(void)setPickeTitle:(NSString *)pickeTitle
{
    self.pickerTitleLabel.text = pickeTitle;
}

#pragma mark piackView 数据源方法
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    NSInteger component;
    if (_isLevelArray) {
        component=_plistArray.count;
    } else if (_isLevelString){
        component=1;
    }else if(_isLevelDic){
        component=[_levelTwoDic allKeys].count*2;
    }else{
        component = 0;
    }
    return component;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    NSArray *rowArray=[[NSArray alloc] init];
    if (_isLevelArray) {
        rowArray=_plistArray[component];
    }else if (_isLevelString){
        rowArray=_plistArray;
    }else if (_isLevelDic){
        NSInteger pIndex = [pickerView selectedRowInComponent:0];
        NSDictionary *dic=_plistArray[pIndex];
        for (id dicValue in [dic allValues]) {
            if ([dicValue isKindOfClass:[NSArray class]]) {
                if (component%2==1) {
                    rowArray=dicValue;
                }else{
                    rowArray=_plistArray;
                }
            }
        }
    }
    return rowArray.count;
}

#pragma mark UIPickerViewdelegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    NSString *rowTitle=nil;
    if (_isLevelArray) {
        rowTitle=_plistArray[component][row];
    }else if (_isLevelString){
        rowTitle=_plistArray[row];
    }else if (_isLevelDic){
        NSInteger pIndex = [pickerView selectedRowInComponent:0];
        NSDictionary *dic=_plistArray[pIndex];
        if(component%2==0)
        {
            rowTitle=_dicKeyArray[row][component];
        }
        for (id aa in [dic allValues]) {
            if ([aa isKindOfClass:[NSArray class]]&&component%2==1){
                NSArray *bb=aa;
                if (bb.count>row) {
                    rowTitle=aa[row];
                }
                
            }
        }
    }
    return rowTitle;
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    if (_isLevelDic&&component%2==0) {
        
        [pickerView reloadComponent:1];
        [pickerView selectRow:0 inComponent:1 animated:YES];
    }
    if (_isLevelString) {
        _resultString=_plistArray[row];
        
    }else if (_isLevelArray){
        _resultString=@"";
        if (![self.componentArray containsObject:@(component)]) {
            [self.componentArray addObject:@(component)];
        }
        for (int i=0; i<_plistArray.count;i++) {
            if ([self.componentArray containsObject:@(i)]) {
                NSInteger cIndex = [pickerView selectedRowInComponent:i];
                _resultString=[NSString stringWithFormat:@"%@%@",_resultString,_plistArray[i][cIndex]];
            }else{
                _resultString=[NSString stringWithFormat:@"%@%@",_resultString,_plistArray[i][0]];
            }
        }
    }else if (_isLevelDic){
        if (component==0) {
            _state =_dicKeyArray[row][0];
        }else{
            NSInteger cIndex = [pickerView selectedRowInComponent:0];
            NSDictionary *dicValueDic=_plistArray[cIndex];
            NSArray *dicValueArray=[dicValueDic allValues][0];
            if (dicValueArray.count>row) {
                _city =dicValueArray[row];
            }
        }
    }
}


/************************重头戏来了************************/
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *myView = nil;
    myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0,  [UIScreen mainScreen].bounds.size.width*0.5, 30)];
    myView.textAlignment = NSTextAlignmentCenter;
    
    if (_isLevelString) {
        myView.text = [_plistArray objectAtIndex:row];
    }else if (_isLevelArray){
        myView.text = [_plistArray objectAtIndex:row];
    }else if (_isLevelDic){
        myView.text = [_dicKeyArray objectAtIndex:row];
    }
    
    myView.font = [UIFont systemFontOfSize:16];//用label来设置字体大小
    myView.textColor = BMUIHexColor(0x333333);
    myView.backgroundColor = [UIColor clearColor];
    return myView;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    return [UIScreen mainScreen].bounds.size.width;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 40.0;
}


-(void)selectObj:(NSString *)obj
{
    int selectIndex = 0;
    for(int i = 0;i<self.plistArray.count ;i++){
        if([obj isEqualToString:self.plistArray[i]]){
            selectIndex = i;
            _selIndex = i;
            break;
        }
    }
    [self.pickerView selectRow:selectIndex inComponent:0 animated:NO];
}

-(void)remove
{
    [UIView animateWithDuration:0.25 animations:^{
         _grayBgView.alpha = 0;
        CGFloat toolViewH = _pickeviewHeight+ZHToobarHeight;
        self.frame = CGRectMake(0,  [UIScreen mainScreen].bounds.size.height,  [UIScreen mainScreen].bounds.size.width, toolViewH);
    } completion:^(BOOL finished) {
         [self removeFromSuperview];
    }];
}

-(void)show
{
    if(!_grayBgView){
        _grayBgView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        _grayBgView.backgroundColor = [UIColor blackColor];
        [[UIApplication sharedApplication].keyWindow addSubview:_grayBgView];
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(remove)];
        [_grayBgView addGestureRecognizer:tapGesture];
    }
    _grayBgView.alpha = 0.4;

    [UIView animateWithDuration:0.25f animations:^{
        CGFloat toolViewH = _pickeviewHeight+ZHToobarHeight;
        self.frame = CGRectMake(0,  [UIScreen mainScreen].bounds.size.height-toolViewH,  [UIScreen mainScreen].bounds.size.width, toolViewH);
    }];
    [[UIApplication sharedApplication].keyWindow addSubview:self];
}

-(void)doneClick
{
    if (_pickerView) {
        if (_resultString) {
            
        }else{
            if (_isLevelString) {
                if(_selIndex>0){
                    _resultString=[NSString stringWithFormat:@"%@",_plistArray[_selIndex]];
                }else{
                    _resultString=[NSString stringWithFormat:@"%@",_plistArray[0]];
                }
            }else if (_isLevelArray){
                _resultString=@"";
                for (int i=0; i<_plistArray.count;i++) {
                    _resultString=[NSString stringWithFormat:@"%@%@",_resultString,_plistArray[i][0]];
                }
            }else if (_isLevelDic){
                if (_state==nil) {
                    _state =_dicKeyArray[0][0];
                    NSDictionary *dicValueDic=_plistArray[0];
                    _city=[dicValueDic allValues][0][0];
                }
                if (_city==nil){
                    NSInteger cIndex = [_pickerView selectedRowInComponent:0];
                    NSDictionary *dicValueDic=_plistArray[cIndex];
                    _city=[dicValueDic allValues][0][0];
                }
                _resultString=[NSString stringWithFormat:@"%@%@",_state,_city];
            }
        }
    }else if(_datePicker){
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSString *currentDateStr = [dateFormatter stringFromDate:_datePicker.date];
        _resultString = [NSString stringWithFormat:@"%@",currentDateStr];
    }
    
    if ([self.delegate respondsToSelector:@selector(toobarDonBtnHaveClick:resultString:)]) {
        [self.delegate toobarDonBtnHaveClick:self resultString:_resultString];
    }
    [self remove];
}

/**
 *  设置PickView的颜色
 */
-(void)setPickViewColer:(UIColor *)color{
    //    _pickerView.backgroundColor=color;
    _pickerView.backgroundColor = [UIColor whiteColor];
}
/**
 *  设置toobar的文字颜色
 */
-(void)setTintColor:(UIColor *)color
{
    _toolbar.tintColor = color;
}
/**
 *  设置toobar的背景颜色
 */
-(void)setToolbarTintColor:(UIColor *)color
{
    _toolbar.barTintColor=color;
}

@end

